import logging

from random import random
from fastapi import BackgroundTasks, FastAPI
from fastapi.responses import JSONResponse, Response
from pydantic import constr
from app.config import PCM_WEB_CLEANUP_CHANCE

from app.models import *
from app.util.pcm import get_packages, get_icon, cleanup
from app.util.urlvalidator import RestrictedHttpUrl
from email.utils import formatdate


pcm = FastAPI()
logger = logging.getLogger(__name__)


def cleanup_task():
    if random() < PCM_WEB_CLEANUP_CHANCE:
        cleanup()


@pcm.get('/packages')
async def packages(repourl: RestrictedHttpUrl, background_tasks: BackgroundTasks):
    background_tasks.add_task(cleanup_task)
    try:
        return JSONResponse(await get_packages(repourl))
    except Exception as e:
        logger.debug("Error in /packages", exc_info=e)
        return {"error": str(e)}


@pcm.get('/icon')
async def icon(
        repourl: RestrictedHttpUrl,
        pkgid: constr(regex=r'^[a-zA-Z][-a-zA-Z0-9.]{0,98}[a-zA-Z0-9]$')):
    try:
        icon_bytes, mtime = await get_icon(repourl, pkgid)
        headers = {
            "content-disposition": f'inline; filename="{pkgid}.png"',
            "content-length": str(len(icon_bytes)),
            "last-modified": formatdate(mtime, usegmt=True)
        }
        return Response(icon_bytes, headers=headers, media_type="image/png")
    except Exception as e:
        logger.debug("Error in /icon", exc_info=e)
        return {"error": str(e)}
